#ifndef _RECORD_H_
#define _RECORD_H_

#include "esp_err.h"
#include "esp_log.h"
#include "stdbool.h"
#include "board.h"
#include "format_wav.h"
#include "lvgl.h"
#include "sys_app.h"
#include "file_iterator.h"
#include "media_service.h"
#include "task_define.h"
#include "msg_manager.h"

#define TAG "RECORD"

#ifdef __cplusplus
extern "C" {
#endif

enum RECORD_MSG_EVENT_CMD {
    RECORD_MSG_CMD_START = 0,
    RECORD_MSG_CMD_STOP,
    RECORD_MSG_CMD_PAUSE,
    RECORD_MSG_CMD_RESUME,
    RECORD_MSG_CMD_EXIT,
};

typedef enum {
    RECORD_STATE_IDLE = 0x00000001,
    RECORD_STATE_RECORDING = 0x00000002,
    RECORD_STATE_PLAYING = 0x00000004,
    RECORD_STATE_PAUSED = 0x00000008,
} record_state_t;

typedef struct {
    FILE *file;
    wav_header_t wav_header;
    char filename[64];
    int16_t i2s_readraw_buff[4096];  // 8KB缓冲区
    size_t buf_pos;                  // 写入缓冲区位置
    uint32_t data_size;
} record_ctx_t;

typedef struct {
    uint16_t track_no;
    uint16_t sum_track_no;
    uint32_t record_time;
    uint32_t last_time;
    int record_state;
    record_ctx_t *record_ctx;  // 动态分配的录音上下文
    TimerHandle_t record_timer; // 录音定时器
    file_iterator_instance_t *file_iterator;
    SemaphoreHandle_t file_mutex;
} record_app_data_t;

void updata_record_ui_time(uint32_t sec);
record_app_data_t* record_get_data(void);
int record_get_current_state(void);
void record_input_event_proc(struct app_msg *msg);
int recorder_meida_init(record_app_data_t* record_app_data);
int recorder_meida_deinit(record_app_data_t* record_app_data);
int recorder_process_data(record_app_data_t* record_app_data);
int recorder_start(record_app_data_t* record_app_data);
int recorder_pause(record_app_data_t* record_app_data);
int recorder_resume(record_app_data_t* record_app_data);
int recorder_stop(record_app_data_t* record_app_data);

void record_iterator_init(record_app_data_t* record_app_data);
void record_iterator_deinit(record_app_data_t* record_app_data);
void record_play_index(record_app_data_t* record_app_data, int index);

void record_view_init(void);
void record_view_exit(void);

#ifdef __cplusplus
}
#endif

#endif /* _RECORD_H_ */
